package com.atguigu.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.yygh.cmn.exceldemo.ExcelReadListener;
import com.atguigu.yygh.cmn.mapper.DictMapper;
import com.atguigu.yygh.cmn.service.DictService;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author:ahang
 * @create:2022-08-30 9:37
 * @Description:
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Autowired
    ExcelReadListener excelReadListener;

    /**
     * value :缓存的命名空间  redis中根据key来进行数据查找
     */
    //@Cacheable(value = "dict",key = "'dict_cache_'+#id")
    @Cacheable(value="dict",key="'dict_cache_'+#id")
    @Override
    public List<Dict> findChildData(Long id) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",id);
        List<Dict> list = baseMapper.selectList(queryWrapper);

        for (Dict dict : list) {
            boolean isChildren = isChildren(dict.getId());
            dict.setHasChildren(isChildren);
        }
        return list;
    }

    /**
     * 判断是否为子节点
     */
    public boolean isChildren(Long id){
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",id);
        Integer integer = baseMapper.selectCount(queryWrapper);
        return integer>0;
    }

    /**
     * 导出数据
     */
    @Override
    public void exportData(HttpServletResponse response) {
        //1、查询dict表中所有的数据
        List<Dict> dictList = baseMapper.selectList(null);

        //2、转泛型 Dict ——> DictEeVo
        List<DictEeVo> dictEeVoList = new ArrayList<>();
        dictList.forEach(dict -> {
            DictEeVo dictEeVo = new DictEeVo();
            BeanUtils.copyProperties(dict,dictEeVo);
            dictEeVoList.add(dictEeVo);
        });


        try {
            //3、设置一些响应头（固定）
            response.setContentType("application/vnd.ms-excel");//excel
            response.setCharacterEncoding("utf-8");
            String fileName = "预约挂号平台数据字典";
            fileName = URLEncoder.encode(fileName,"utf-8");
            response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");

            //4、使用EasyExcel完成数据导出
            // 参数1：响应流
            EasyExcel.write(response.getOutputStream(),DictEeVo.class)
                    .sheet("数据字典")
                    .doWrite(dictEeVoList);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 数据导入
     */
    @CacheEvict(value = "dict",allEntries = true)
    @Override
    public void inportData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, excelReadListener)
                    .sheet() //选择第一个sheet表进行读取
                    .doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据parentdiccode和value来查找对应的名称
     * @param parentDictCode
     * @param value
     * @return
     */
    @Override
    public String getNameByParentDictCodeAndValue(String parentDictCode, String value) {
        //省市区不需要dictcode  医院等级需要dictcode
        if(StringUtils.isEmpty(parentDictCode)){
            QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("value",value);
            Dict dict = baseMapper.selectOne(queryWrapper);
            if(dict!=null){
                return dict.getName();
            }
        }else{
            Dict dictByDictcode = getDictByDictcode(parentDictCode);
            Long id = dictByDictcode.getId();
            QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("value",value);
            queryWrapper.eq("parent_id",id);
            Dict dict = baseMapper.selectOne(queryWrapper);

            if(dict!=null){
                return dict.getName();
            }
        }

        return "";
    }

    /**
     * 根据dictcode查询dict对象
     */
    private Dict getDictByDictcode(String dictCode){
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dict_code",dictCode);
        Dict dict = baseMapper.selectOne(queryWrapper);

        return dict;
    }

    //根据dictcode查询所有省份
    @Override
    public List<Dict> findByDictcode(String dictCode) {
        Dict dict = this.getDictByDictcode(dictCode);
        Long id = dict.getId();

        List<Dict> childData = this.findChildData(id);
        return childData;
    }


}
